package com.topisv.tms.service.workBox;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.workBox.WorkBox;
import com.topisv.tms.repository.workBox.WorkBoxDao;

@Component
@Transactional(readOnly = true)
public class WorkBoxService {

	@Autowired
	private WorkBoxDao workBoxDao;

	public List<WorkBox> loadAll() {
		return (List<WorkBox>) this.workBoxDao.findAll();
	}

	@Transactional(readOnly = false)
	public void save(WorkBox box) {
		this.workBoxDao.save(box);
	}

	public List<WorkBox> loadByCondition(String customerCode,String warehouseCode) {
		Specification<WorkBox> spec = getWhereClause(customerCode,warehouseCode);
		List<WorkBox> lightShelfList= this.workBoxDao.findAll(spec);
		return lightShelfList;
	}
	
	/**
	 * 查询条件封装
	 * @param param
	 * @return
	 */
	private Specification<WorkBox> getWhereClause(final String customerCode,final String warehouseCode) {
		
		return new Specification<WorkBox>(){
			
		    @Override
		    public Predicate toPredicate(Root<WorkBox> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
		      Predicate pre = cb.conjunction();
		      
		      if(StringUtils.isNotEmpty(customerCode)){
					pre.getExpressions().add(cb.equal(r.get("customerCode"),customerCode));
			  }

		      if(StringUtils.isNotEmpty(warehouseCode)){
		    	  pre.getExpressions().add(cb.equal(r.get("warehouseCode"),warehouseCode));
		      }
		      
		      return pre;
		    }
		  };
       }

	/*
	 * 删除
	 */
	@Transactional(readOnly = false)
	public void delete(Long boxId) {
		WorkBox box=this.workBoxDao.findOne(boxId);
		this.workBoxDao.delete(box);
	}
	
	/**
	 * 释放
	 * @param lightShelfId
	 * @throws Exception 
	 */
	@Transactional(readOnly = false)
	public void free(Long boxId) throws Exception {
		WorkBox box=this.workBoxDao.findOne(boxId);
		box.setTaskCode(null);
		box.setStatus("free");
	}

	public WorkBox loadBoxByCode(String boxCode) {
		return this.workBoxDao.loadByBoxCode(boxCode);
	}
		
		

}
